import {
  reqFindPassword,
  reqLogin,
  reqRegister,
  reqSendCode,
} from "@/api/index";
import { ref, onMounted } from "vue";
import router from "@/router/index";
import { ElMessage } from "element-plus";
import { useUserStore } from "@/store/index";
import { createCdHelper } from "@/utils/index";

export const useLoginForm = () => {
  const loading = ref(false);
  const form = ref({
    email: "",
    password: "",
    googleCode: "",
  });
  const formRules = ref({
    email: [{ required: "true", message: "賬戶不能爲空", trigger: "blur" }],
    password: [{ required: "true", message: "密碼不能爲空", trigger: "blur" }],
    googleCode: [
      { required: "true", message: "谷歌驗證器不能为空", trigger: "blur" },
    ],
  });

  const submitForm = (formDom) => {
    formDom.value.validate(async (valid) => {
      if (valid) {
        clog("登录表单:", form.value);
        loading.value = true;
        try {
          // 1. 发起登录请求
          const loginRes = await reqLogin({
            mail: form.value.email,
            code: form.value.googleCode,
            // code: "66669999", // 测试用
            password: form.value.password,
          });
          loading.value = false;
          clog("登录结果:", loginRes);
          // 2. 登录成功后，跳转到相应页面
          ElMessage.success("登录成功");
          const userStore = useUserStore();
          userStore.setUserInfo({
            mail: loginRes.mail,
            user_id: loginRes.user_id,
            token: loginRes.token,
          });
          router.push("/home");
        } catch (err) {
          clog("登录失败：", err);
          loading.value = false;
        }
      }
    });
  };

  return {
    loading,
    form,
    formRules,
    submitForm,
  };
};

export const useRefindPwd = () => {
  const form = ref({
    email: "",
    password: "",
    passwordConfirm: "",
    googleCode: "",
  });
  const validateConfirmPassword = (rule, value, callback) => {
    if (value !== form.value.password) {
      callback(new Error("確認密碼不正確"));
    } else {
      callback();
    }
  };
  const formRules = ref({
    email: [{ required: "true", message: "賬戶不能爲空", trigger: "blur" }],
    password: [{ required: "true", message: "密碼不能爲空", trigger: "blur" }],
    passwordConfirm: [
      { required: "true", message: "確認密碼不能爲空", trigger: "blur" },
      { validator: validateConfirmPassword, trigger: "blur" },
    ],
    googleCode: [
      { required: "true", message: "谷歌騐証碼不能爲空", trigger: "blur" },
    ],
  });

  const loading = ref(false);
  const submitForm = (formDom, toLogin) => {
    // 1.表单验证
    formDom.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        // 2.提交表单数据
        const res = await reqFindPassword({
          mail: form.value.email,
          password: form.value.password,
          code: form.value.googleCode,
        });
        clog("找回密码成功:", res);
        loading.value = false;
        ElMessage.success("找回密码成功，請重新登錄");
        toLogin();
      }
    });
  };

  return {
    loading,
    form,
    formRules,
    submitForm,
  };
};

export const useRegisterForm = () => {
  const CD_SECOND = 3; // 验证码CD时间
  const CD_TEXT = "發送驗證碼";
  let cdLock = false;

  const registerStep = ref(1); // 取值 1|2
  const setRegisterStep = (step) => {
    registerStep.value = step;
  };

  const validateConfirmPassword = (rule, value, callback) => {
    if (value !== form.value.password) {
      callback(new Error("確認密碼不正確"));
    } else {
      callback();
    }
  };
  const validateGoogleCode = (rule, value, callback) => {
    if (value !== tmpGoogleCode) {
      callback(new Error("谷歌驗證碼不正確"));
    } else {
      callback();
    }
  };
  let tmpGoogleCode; // 暂存谷歌验证码，用于校验界面上的验证码是否正确
  const form = ref({
    email: "",
    password: "",
    passwordConfirm: "",
    mailCode: "",
    googleCode: "",
  });

  const formRules = ref({
    email: [{ required: "true", message: "賬戶不能爲空", trigger: "blur" }],
    password: [{ required: "true", message: "密碼不能爲空", trigger: "blur" }],
    passwordConfirm: [
      { required: "true", message: "確認密碼不能爲空", trigger: "blur" },
      { validator: validateConfirmPassword, trigger: "blur" },
    ],
    mailCode: [
      { required: "true", message: "郵箱騐証碼不能爲空", trigger: "blur" },
    ],
    googleCode: [
      { required: "true", message: "谷歌騐証碼不能爲空", trigger: "blur" },
      { validator: validateGoogleCode, trigger: "blur" },
    ],
  });

  const loading = ref(false);
  const submitForm = (formDom) => {
    // 1.表单验证
    formDom.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        try {
          // 2.提交表单数据
          const res = await reqRegister({
            mail: form.value.email,
            password: form.value.password,
            code: form.value.mailCode,
          });
          loading.value = false;
          clog("注册成功:", res);
          tmpGoogleCode = res.google_secret;
          // 回显谷歌验证码
          form.value.googleCode = res.google_secret;
          // 切换到第二步
          setRegisterStep(2);
        } catch (err) {
          clog("注册失败：", err);
          loading.value = false;
        }
      }
    });
  };
  const finishRegister = (toLogin) => {
    ElMessage.success("恭喜您，註冊成功！");
    toLogin();
  };
  const cdHelper = createCdHelper(CD_SECOND);
  const cdText = ref(CD_TEXT);
  const startCD = () => {
    cdHelper.startCD(
      (remainSecond) => {
        cdText.value = `${remainSecond}s`;
      },
      () => {
        cdText.value = CD_TEXT;
      }
    );
  };
  const sendMailCode = async () => {
    if (!form.value.email) {
      ElMessage.error("郵箱不能爲空");
      return;
    }

    // 0.判断当前如果正在CD中，则不发送请求
    if (CD_TEXT !== cdText.value || cdLock) {
      return;
    }
    cdLock = true;
    // 1.发送邮件验证
    const sendCodeRes = await reqSendCode(form.value.email);
    cdLock = false;
    clog("发送验证码：", sendCodeRes);
    ElMessage.success("郵箱驗證碼已發送");
    // 2.设置倒计时
    startCD();
  };
  onMounted(() => {
    if (cdHelper.checkIsCD()) {
      startCD();
    }
  });

  return {
    registerStep,
    cdText,
    loading,
    form,
    formRules,
    sendMailCode,
    submitForm,
    finishRegister,
  };
};
